package com.chengliang.bbs.service.impl;
import com.chengliang.bbs.entry.Practice;
import com.chengliang.bbs.mapper.ContinuityPracticeMapper;
import com.chengliang.bbs.mapper.ExperienceMapper;
import com.chengliang.bbs.mapper.ExperienceRecordMapper;
import com.chengliang.bbs.mapper.PracticeMapper;
import com.chengliang.bbs.service.PracticeService;
import com.chengliang.bbs.type.ExperienceType;
import com.chengliang.bbs.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: chengliang
 * @create: 2019-07-31 09:24
 */
@Slf4j
@Service
public class PracticeServiceImpl implements PracticeService {

    @Autowired
    private PracticeMapper practiceMapper;

    @Autowired
    private ContinuityPracticeMapper continuityPracticeMapper;

    @Autowired
    private ExperienceMapper experienceMapper;

    @Autowired
    private ExperienceRecordMapper experienceRecordMapper;

    @Override
    public List<Practice> getPracticeByUserId(Integer userId) {
        if(StringUtil.isEmpty(userId)){
            return null;
        }
        return practiceMapper.selectPracticeByUserId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean practiceByUserId(Integer userId) {
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        //签到表添加记录
        practiceMapper.insertSelective(new Practice().setUserId(userId).setPracticeTime(now));
        //修改连续签到信息
        if (continuityPracticeMapper.isPracticeDayBefore(userId)) {
            //连续签到
            continuityPracticeMapper.practiceDayNumberAddOne(userId, now);
        } else {
            //断签
            continuityPracticeMapper.practiceDayNumberOne(userId, now);
        }
        //计算经验
        Integer experience = continuityPracticeMapper.selectContinuityPracticeByUserId(userId).getNowDayExperience();
        log.info("获取的经验值{}",experience);
        //添加经验
        experienceMapper.addTotalExperience(userId,experience);
        //添加经验记录
        experienceRecordMapper.insertExperienceRecord(userId,experience, ExperienceType.practice);
        return true;
    }

    @Override
    public boolean isNowDayPracticed(Integer userId) {
        return practiceMapper.selectIsPracticeByUserId(userId);
    }


}
